import 'dart:async';

import 'package:chathouse/model/shield.dart';
import 'package:chathouse/pages/expert/confirm_service.dart';
import 'package:chathouse/pages/expert/service_detail.dart';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../public/empty_widget.dart';
import '../../public/event_bus.dart';
import '../base/base.dart';

///专家服务列表
class ServiceListPage extends BaseStatefulWidget {
  const ServiceListPage({Key? key}) : super(key: key);

  @override
  _ServiceListPageState createState() => _ServiceListPageState();
}

class _ServiceListPageState extends BaseStatefulWidgetState<ServiceListPage>
    with AutomaticKeepAliveClientMixin {
  Shield? shield;

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false); // 刷新控件控制
  StreamSubscription? refreshSubscription;

  List<Rows>? rows = [];

  @override
  bool get wantKeepAlive => true;

  int pageNum = 1;

  @override
  void initState() {
    super.initState();
    updateEmptyPage(tipTitle: "暫無服務數據");
    updateState(LoadState.success);
    setState(() {
      scaffoldBackColor = Colors.white;
    });

    refreshSubscription = eventBus.on<UpdateExpertSerivce>().listen((event) {
      pageNum = 1;
      rows?.clear();
      loadService();
    });
    loadService();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    refreshSubscription?.cancel();
  }

  loadMore() {
    pageNum += 1;
    loadService();
  }

  clearLoad() {
    pageNum = 1;
    rows?.clear();
    loadService();
  }

  void loadService() {
    final params = {
      "pageNum": pageNum,
    };
    Obj.showLoading();
    Apis.Shieldlist(params)
        .then((response) => {
              _refreshController.refreshCompleted(),
            _refreshController.loadComplete(),
              Obj.dismissLoading(),
              shield = Shield.fromJson(response?.data),
              rows?.addAll(shield?.rows ?? []),
              setState(() {})
            })
        .onError((error, stackTrace) => {
              _refreshController.refreshCompleted(),
              _refreshController.loadComplete(),
              updateState(LoadState.empty),
              Obj.dismissLoading()
            });
  }

  Widget item(idx) {
    Rows? row = rows?[idx];
    return InkWell(
      onTap: () => {
        if (row?.quote == true || row?.readFlag == "1")
          {Get.to(ExpertServiceDetailPage(row!.projectId!))}
        else
          {
            Get.to(ConFirmService(row!.projectId!, row!.serviceName!)),
          }
      },
      child: Container(
        padding: EdgeInsets.symmetric(vertical: Styles.magin_16),
        child: Row(
          children: [
            (row?.memberImage ?? "").isNotEmpty ? ImageUtils.image(row?.memberImage ?? "",
                    width: 55.w,
                    height: 55.w,
                    imageType: ImageType.NETWORK,
                    radius: 30.w)
                .setContainer(margin: EdgeInsets.only(right: Styles.magin_12))
            : ImageUtils.image('assets/images/expert_avatar.png',
                width: 55.w,
                height: 55.w,
                imageType: ImageType.ASSET,
                radius: 30.w)
                .setContainer(margin: EdgeInsets.only(right: Styles.magin_12))
            ,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(row?.membersName ?? "",
                      style: getTextStyle(
                        20.w,
                        fontType: FontType.BOLD,
                        color: Styles.c_333,
                      )),
                  const SizedBox(
                    height: 6,
                  ),
                  Text(row?.serviceName ?? "",
                      style: getTextStyle(
                        16.w,
                        fontType: FontType.BOLD,
                        color: Styles.c_333,
                      )),
                ],
              ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              // mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(row?.createTime ?? "",
                    style: getTextStyle(
                      12.w,
                      color: Styles.c_999,
                    )),
                const SizedBox(
                  height: 14,
                ),
                Visibility(
                  visible: (row?.readFlag == "0"),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text("新消息",
                          style: getTextStyle(14.sp,
                              fontType: FontType.BOLD,
                              color: Colors.redAccent)),
                      const SizedBox(
                        width: 4,
                      ),
                      Container(
                        width: 6,
                        height: 6,
                        decoration: BoxDecoration(
                            color: Colors.redAccent,
                            borderRadius: BorderRadius.circular(3)),
                      )
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: rows?.length == 0 ? const Align(
        child: EmptyWidget(
          emptyText: '暂無服務數據',
        ),
        alignment: Alignment.center,
      ) : SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        controller: _refreshController,
        onRefresh: clearLoad,
        onLoading: () {
          loadMore();
        },
        child: ListView.separated(
            itemBuilder: (context, index) {
              return item(index);
            },
            separatorBuilder: (context, index) {
              return Container(
                height: 0.6,
                color: Styles.cf3,
              );
            },
            itemCount: rows?.length ?? 0),
      ),
    );
  }
}
